<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <!--       <el-form-item label="健身房id" prop="gymId">
            <el-input v-model="queryParams.gymId" placeholder="请输入健身房id" clearable style="width: 220px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="团课" prop="classId">
            <el-select v-model="queryParams.classId" placeholder="请选择" @keyup.enter="handleQuery" clearable filterable>
              <el-option v-for="dict in leagueClassList" :key="dict.id" :label="dict.leagueClassName"
                :value="dict.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教练" prop="coachId">
            <el-select v-model="queryParams.coachId" placeholder="请选择" @keyup.enter="handleQuery" filterable clearable>
              <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName" :value="dict.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker clearable v-model="queryParams.startDate" type="date" value-format="YYYY-MM-DD 00:00:00"
              placeholder="请选择开始日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker clearable v-model="queryParams.endDate" type="date" value-format="YYYY-MM-DD 23:59:59"
              placeholder="请选择结束日期">
            </el-date-picker>
          </el-form-item>
          <!--        <el-form-item label="课程日期" prop="courseDate">
            <el-date-picker clearable
              v-model="queryParams.courseDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择课程日期"
            />
          </el-form-item> -->
          <!--          <el-form-item label="最近预约" prop="courseDate">
            <el-date-picker clearable
              v-model="queryParams.courseDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择课程日期"
            />
          </el-form-item> -->
          <!--     <el-form-item label="是否可以预约，0-不可以；1-可以" prop="isReservation">
            <el-input v-model="queryParams.isReservation" placeholder="请输入是否可以预约，0-不可以；1-可以" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--         <el-form-item label="预约情况" prop="reservationSituation">
            <el-input v-model="queryParams.reservationSituation" placeholder="请输入预约情况" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['primary:gymReservation:add']">新增</el-button>
          </el-col>
          <!--          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['primary:gymReservation:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['primary:gymReservation:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['primary:gymReservation:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="gymReservationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="会员名称" align="center" prop="memberName" /> -->
        <el-table-column label="团课名称" align="center" prop="leagueClassName" />
        <!-- <el-table-column label="教练名称" align="center" prop="coachName" /> -->
        <el-table-column label="预约日期" align="center" prop="courseDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.courseDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" align="center" prop="reservationStartTime" />
        <el-table-column label="结束日期" align="center" prop="reservationEndTime" />
        <!-- <el-table-column label="是否可以预约" align="center" prop="isReservation">
          <template v-slot="{ row }">
            {{ row.isReservation == 0 ? '不可以' : '可以' }}
          </template>
        </el-table-column> -->
        <el-table-column label="星期几" align="center" prop="isReservation">
          <template #default="scope">
            <dict-tag :options="g_week_type" :value="scope.row.planPerWeek" />
          </template>
        </el-table-column>
        <el-table-column label="预约情况" align="center">
          <template #default="{ row }">
            {{ row.reservationSituation }}/{{ row.classPeopleNum }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:gymReservation:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:gymReservation:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="添加预约" placement="top">
              <el-button link type="primary" icon="Finished" @click="handleyuyue(scope.row)"
                v-hasPermi="['primary:gymReservation:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" /> -->
    </el-card>
    <!-- 添加或修改团课预定日期对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="550px" append-to-body>
      <el-form ref="gymReservationFormRef" :model="form" :rules="rules" label-width="110px">

        <!--        <el-form-item label="预约人电话" v-if="dialog.isyuyue==true">
          <el-input v-model="viplist.phoneNumber" placeholder="请输入电话" clearable style="width: 215px" type="number"
            :min="11" />
          <el-button type="primary" icon="Search" @click="getListd" style="margin-left: 10px;">搜索</el-button>
        </el-form-item> -->
        <!--        <el-form-item label="选择预约人" v-if="isshow==3">
          <el-select v-model="viplist.memberId" placeholder="请选择" clearable filterable>
            <el-option v-for="dict in memberList" :key="dict.id" :label="dict.memberName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item> -->


        <el-form-item label="选择会员" prop="memberId" v-if="isshow==3">
          <!-- <span>{{viplist.memberId}}</span> -->
          <el-select ref="selectRef" v-model="viplist.memberId" placeholder="请选择" filterable clearable v-if="isSearch">
            <el-option v-for="dict in memberList" :key="dict.id" :label="dict.memberName" :value="dict.id"></el-option>
          </el-select>
          <el-input v-model="form.memberName" placeholder="请输入会员名进行搜索" type="text" style="width: 215px;" v-else />
          <el-button type="primary" icon="Search" @click="getListvip(form.memberName)">搜索</el-button>
        </el-form-item>


        <el-form-item label="团课名称" prop="classId" v-if="isshow!=2">
          <el-select v-model="form.classId" placeholder="请选择" :disabled='dialog.isyuyue' clearable filterable>
            <el-option v-for="dict in leagueClassList" :key="dict.id" :label="dict.leagueClassName"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教练名称" prop="coachId">
          <el-select v-model="form.coachId" placeholder="请选择" :disabled='dialog.isyuyue' clearable filterable>
            <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate" v-if="isshow==1">
          <el-date-picker clearable v-model="form.startDate" type="date" value-format="YYYY-MM-DD 00:00:00"
            placeholder="请选择开始日期" :disabled='dialog.isyuyue'>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate" v-if="isshow==1">
          <el-date-picker clearable v-model="form.endDate" type="date" value-format="YYYY-MM-DD 23:59:59"
            placeholder="请选择结束日期" :disabled='dialog.isyuyue'>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上课时间" prop="reservationStartTime" v-if="isshow!=2">
          <el-time-select v-model="form.reservationStartTime" style="width: 215px" :max-time="form.reservationEndTime"
            class="mr-4" placeholder="请选择上课时间" start="01:00" step="00:15" end="23:59" :disabled='dialog.isyuyue' />
          <!-- <el-time-select v-model="form.reservationEndTime" style="width: 120px;margin-left: 10px;"
            :min-time="form.reservationStartTime" placeholder="结束时间" start="08:30" step="00:15" end="18:30" /> -->
        </el-form-item>



        <el-form-item label="预约日期周几" prop="planPerWeek" v-if="isshow==1">
          <el-radio-group v-model="form.planPerWeek">
            <el-radio v-for="weekday in dataa.weekdays" :key="weekday.value" :label="weekday.value">
              {{ weekday.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否可预约" prop="isReservation" v-if="isshow==1">
          <!-- <el-input v-model="form.isReservation" placeholder="请输入是否可以预约，0-不可以；1-可以" type="number" :min="0" /> -->
          <el-radio-group v-model="form.isReservation">
            <el-radio v-for="isor in dataa.isReservation" :key="isor.value" :label="isor.value">
              {{ isor.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="金额" v-if="isshow==1 || isshow==2">
          <el-input v-model="form.price" placeholder="请输入金额" clearable style="width: 215px" type="number" :min="0" />
        </el-form-item>

      </el-form>
      <el-card shadow="never" v-if="isshow==3">
        <el-table v-loading="loading" :data="form.memberList">
          <el-table-column label="会员姓名" align="center" prop="memberName" />
          <el-table-column label="会员手机" align="center" prop="phoneNumber" />
          <el-table-column label="会员卡名称" align="center" prop="cardName" />
        </el-table>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForma" v-if="isshow==3">确定预约</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-else>确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GymReservation" lang="ts">
  import api from "@/api/system/user"
  import { watch, nextTick } from 'vue';
  import { listGymReservation, getGymReservation, delGymReservation, addGymReservation, updateGymReservation, getyuyue } from '@/api/primary/gymReservation';
  import { listMember } from '@/api/primary/member';
  import { listRole } from "@/api/system/role";
  import { listCoach } from '@/api/primary/coach';
  import { listLeagueClass } from '@/api/primary/leagueClass';
  import { GymReservationVO, GymReservationQuery, GymReservationForm } from '@/api/primary/gymReservation/types';
  import { LeagueClassVO } from '@/api/primary/leagueClass/types';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { g_week_type } = toRefs<any>(proxy?.useDict("g_week_type"));
  const leagueClassList = ref<LeagueClassVO[]>([]);
  const coachList = ref<any>([]);
  const isshow = ref(0);
  const selectRef = ref(null);
  const isSearch = ref(true);
  const memberList = ref<any>([]);
  const gymReservationList = ref<any>([]);
  const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const idsname = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const roleId = ref(0);
  const roleCan = ref<any>();
  const roleList = ref<any>();
  const defaultTime = ref<[Date]>([
    new Date(2000, 1, 1, 0, 0, 0),
    // new Date(2000, 2, 1, 23, 59, 59),
  ])
  const queryFormRef = ref<ElFormInstance>();
  const gymReservationFormRef = ref<ElFormInstance>();
  //

  const dialog = reactive<DialogOption>({
    visible: false,
    title: '',
    istrue: false,
    isyuyue: false
  });
  const radio1 = ref('1')
  const initFormData : GymReservationForm = {
    id: undefined,
    price: undefined,
    gymId: undefined,
    memberList: undefined,
    memberName: undefined,
    classId: undefined,//团课id
    classPeopleNum: undefined,//课程人数
    coachId: undefined,//教练id
    startDate: undefined,//开始时间
    endDate: undefined,//结束时间
    reservationStartTime: undefined,//开始时间
    reservationEndTime: undefined,//结束时间
    courseDate: undefined,//课程日期
    planPerWeek: undefined,//
    isReservation: undefined,//是否可以预约，0-不可以；1-可以
    reservationSituation: undefined,//预约情况
  }
  const dataa = reactive({
    weekdays: [ // 星期几的选项
      { value: 2, label: '周一' },
      { value: 3, label: '周二' },
      { value: 4, label: '周三' },
      { value: 5, label: '周四' },
      { value: 6, label: '周五' },
      { value: 7, label: '周六' },
      { value: 1, label: '周日' }
    ],
    isReservation: [ // 是否可预约
      { value: '0', label: '不可以' },
      { value: '1', label: '可以' },
    ],
  })
  const viplist = reactive<any>({
    id: undefined,
    memberId: undefined,
    memberName: undefined,
    phoneNumber: undefined,
    classId: undefined,
    memberType: 0,
  });
  const data = reactive<PageData<GymReservationForm, GymReservationQuery>>({
    form: { ...initFormData },
    queryParams: {
      // pageNum: 1,
      // pageSize: 10,
      memberName: undefined,
      gymId: undefined,
      memberId: undefined,
      planPerWeek: undefined,
      classId: undefined,
      coachId: undefined,
      reservationStartTime: undefined,
      reservationEndTime: undefined,
      startDate: undefined,//开始时间
      endDate: undefined,//结束时间
      courseDate: undefined,
      isReservation: undefined,
      reservationSituation: undefined,
      userName: '',
      phonenumber: '',
      status: '',
      deptId: '',
      params: {
      }
    },
    rules: {
      id: [
        { required: true, message: "id不能为空", trigger: "change" }
      ],
      gymId: [
        { required: true, message: "健身房id不能为空", trigger: "change" }
      ],
      classId: [
        { required: true, message: "团课id不能为空", trigger: "change" }
      ],
      memberId: [
        { required: true, message: "会员不能为空", trigger: "blur" }
      ],
      coachId: [
        { required: true, message: "教练id不能为空", trigger: "change" }
      ],
      reservationStartTime: [
        { required: true, message: "每天几点开始时间不能为空", trigger: "blur" }
      ],
      // reservationEndTime: [
      //   { required: true, message: "结束时间不能为空", trigger: "blur" }
      // ],
      startDate: [
        { required: true, message: "开始时间不能为空", trigger: "blur" }
      ],
      endDate: [
        { required: true, message: "结束时间不能为空", trigger: "blur" }
      ],
      courseDate: [
        { required: true, message: "课程日期不能为空", trigger: "blur" }
      ],
      isReservation: [
        { required: true, message: "是否可以预约不能为空", trigger: "change" }
      ],
      reservationSituation: [
        { required: true, message: "已预约人数不能为空", trigger: "change" }
      ],
      planPerWeek: [
        { required: true, message: "预约日期为每周几不能为空", trigger: "blur" }
      ],
    }
  });

  const formatReservationStatus = (row : any, column : any) => {
    return row.isReservation == 0 ? '不可以' : '可以';
  };
  watch(() => viplist.memberId, (newVal, oldVal) => {
    if (newVal == '') {
      isSearch.value = false
      form.value.memberName = ''
    }
  });
  /** 查询会员信息列表 */
  const getListvip = async () => {
    console.log(form.value.memberName, 'form.value.memberNameform.value.memberName')
    if (form.value.memberName == undefined) {
      proxy?.$modal.msgSuccess("请先输入会员名再进行搜索");
      return
    }
    const res = await listMember(form.value);
    memberList.value = res.rows;


    console.log(memberList.value, '正式会员表')
    if (memberList.value.length == 0) {
      isSearch.value = false
      proxy?.$modal.msgError("未搜索到该会员，请重新搜索");
    } else {

      isSearch.value = true
      openSelectDropdown()
      proxy?.$modal.msgSuccess("请选择匹配到的会员");
    }

  }
  function openSelectDropdown() {
    nextTick(() => {
      if (selectRef.value) {
        selectRef.value.focus(); // 这将打开下拉选择框
      }
    });
  }
  const { queryParams, form, rules } = toRefs(data);
  /** 查询团课信息列表 */
  const getLista = async () => {
    // queryParams.value.startDate=''
    // queryParams.value.endDate=''
    loading.value = true;
    const res = await listLeagueClass(queryParams.value);
    leagueClassList.value = res.rows;
    console.log(leagueClassList.value, '课程信息表')
    loading.value = false;
  }

  /** 查询团课预定日期列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listGymReservation(queryParams.value);
    gymReservationList.value = res.data;
    console.log(gymReservationList.value, '预约列表')
    //total.value = res.total;
    loading.value = false;
  }


  /**
   * 查询教练列表
   */
  const getListb = async () => {
    console.log('111111')
    const res = await listCoach(queryParams.value);
    coachList.value = res.rows;
    console.log(coachList.value, '教练信息表')
  }
  /** 取消按钮 */
  const cancel = () => {
    reset();
    viplist.memberId = ''
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    gymReservationFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : GymReservationVO[]) => {
    ids.value = selection.map(item => item.id);
    idsname.value = selection.map(item => item.leagueClassName);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    isshow.value = 1
    dialog.isyuyue = false;
    dialog.visible = true;
    dialog.istrue = true;
    dialog.title = "添加团课预定日期";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: GymReservationVO) => {
    isshow.value = 2
    dialog.istrue = false;
    dialog.isyuyue = false;
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getGymReservation(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改团课预定日期";
  }
  // 预约
  const handleyuyue = async (row ?: GymReservationVO) => {
    isSearch.value = false
    isshow.value = 3
    viplist.id = row.id
    dialog.isyuyue = true;
    dialog.visible = true;
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getGymReservation(_id);
    Object.assign(form.value, res.data);
    dialog.title = "添加会员预约";
  }
  // 会员上课预约预约
  const submitForma = async () => {
    viplist.classId = form.value.classId
    const res = await getyuyue(viplist);
    proxy?.$modal.msgSuccess("添加成功")
    dialog.visible = false;
    viplist.memberId = ''
    await getList();
  }
  /** 提交按钮 */
  const submitForm = () => {
    gymReservationFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateGymReservation(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          await addGymReservation(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("添加成功");
          queryParams.value.classId = ''
          queryParams.value.coachId = ''
        }

        dialog.visible = false;
        await getList();
      }
    });
  }
  // 查询会员列表
  // const getListd = async () => {
  //   console.log(viplist, '会员列表请求参数')
  //   const res = await listMember(viplist);
  //   memberList.value = res.rows;

  // }
  /** 删除按钮操作 */
  const handleDelete = async (row ?: GymReservationVO) => {
    const _ids = row?.id || ids.value;
    const name = row?.leagueClassName || idsname.value;
    await proxy?.$modal.confirm('是否确认删除团课名称为"' + name + '"的数据项？').finally(() => loading.value = false);
    await delGymReservation(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('primary/gymReservation/export', {
      ...queryParams.value
    }, `gymReservation_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    // 获取当前日期
    const currentDate = new Date();
    // 获取当前日期的星期几（0 表示周日，1 表示周一，以此类推）
    let currentDayOfWeek = currentDate.getDay();
    // 将星期日的索引（0）转换为 7，以便于后续计算
    if (currentDayOfWeek === 0) {
      currentDayOfWeek = 7;
    }
    // 计算最近一周的开始日期
    const startOfWeek = new Date(currentDate);
    startOfWeek.setDate(currentDate.getDate() - currentDayOfWeek + 1); // 从本周的星期一开始
    // 计算最近一周的结束日期
    const endOfWeek = new Date(startOfWeek);
    endOfWeek.setDate(startOfWeek.getDate() + 6);
    // 将日期格式转换为 ISO 8601 格式的字符串
    const startISOString = startOfWeek.toISOString();
    const endISOString = endOfWeek.toISOString();
    // 提取日期部分，忽略时间部分
    const start = startISOString.split('T')[0];
    const end = endISOString.split('T')[0];
    // 将日期格式从 yyyy-mm-dd 转换为 yyyy-mm-dd 00:00:00
    let formattedStartDate = start + ' 00:00:00';
    let formattedEndDate = end + ' 23:59:59';
    queryParams.value.startDate = formattedStartDate
    queryParams.value.endDate = formattedEndDate
    console.log("最近一周的开始日期是aa：" + queryParams.value.startDate);
    console.log("最近一周的结束日期是bb：" + queryParams.value.endDate);

    queryParams.value.pageNum = undefined
    queryParams.value.pageSize = undefined
    getLista()
    getListb()
    // getListd()
    queryParams.value.pageNum = 1
    queryParams.value.pageSize = 10
    getList();
  });
</script>
